package com.xpgk.sbwx.servlet.beingServed;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xpgk.mvc.bentryRegister.Customer;
import com.xpgk.sbwx.login.WXLoginController;
import com.xpgk.sbwx.util.AuthUtil;

import net.sf.json.JSONObject;

public class BeingServerCallBackServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String organids = "";
		String code = req.getParameter("code");
		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+AuthUtil.APPID
				+ "&secret="+AuthUtil.APPSECRET
				+ "&code="+code
				+ "&grant_type=authorization_code";
		JSONObject jsonObject = AuthUtil.doGetJson(url);
		String openid = jsonObject.getString("openid");
		String sql2 = "SELECT * FROM sb_customer where openid = ? AND dataStatus in ('1','2')";
		Customer cus = Customer.dao.findFirst(sql2,openid);
		if(cus!=null){
			organids = cus.getStr(Customer.column_organIds);
		}
		String token = jsonObject.getString("access_token");
		String infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token="+token
				+ "&openid="+openid
				+ "&lang=zh_CN";
		JSONObject userInfo = AuthUtil.doGetJson(infoUrl);
		/*System.out.println(userInfo);*/
		req.setCharacterEncoding("utf-8");
		req.setAttribute("organids", organids);
		req.setAttribute("openid", userInfo.getString("openid"));// 为request对象添加参数
		
		RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/view/sbwx/parts.jsp"); // 使用req对象获取RequestDispatcher对象
        dispatcher.forward(req, resp); 
		/*WXLoginController wxc = new WXLoginController();
		wxc.index();*/
		//super.doGet(req, resp);
	}
	
	

}
